package com.fengye.algorithms.leecode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author fengye
 * @Date 2023/4/8 10:09
 **/
public class GenerateParenthesis22 {

    public static void main(String[] args) {
        GenerateParenthesis22 main = new GenerateParenthesis22();
        System.out.println(main.generateParenthesis(3));
    }

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        dfs(result, new StringBuilder(), 0, 0, n);
        return result;
    }

    public void dfs(List<String> result, StringBuilder sb,  int left, int right, int max) {
        if(sb.length() == 2*max) {
            result.add(sb.toString());
            return;
        }
        if(left < max) {
            dfs(result, sb.append('('), left + 1, right, max);
            sb.deleteCharAt(sb.length() - 1);
        }
        if(right < left ) {
            dfs(result, sb.append(')'), left, right + 1, max);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
